package com.example.client_anna.base;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.client_anna.module.MainActivity;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
//BaseActivity类继承AppCompatActivity类,成为其他Activity的父类
public class BaseActivity extends AppCompatActivity {

    private ForceOfflineReceiver receiver;

    //其他活动继承BaseActivity后对活动进行注册
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册
        ActivityCollector.addActivity(this);
    }

    //活动第一次创建的时候在onCreate()后面运行
    //打开下一个界面，上一个界面不finish，按Back健回到上一个界面时，调用onResume()
    //切换APP后在切回来的时候调用onResume()
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE");
        receiver = new ForceOfflineReceiver();
        registerReceiver(receiver,intentFilter);
    }

    //在Activity A中启动Activity B，如果B的活动页面覆盖在Activity A上方时，那么Activity A则会调用onPause()
    //不是处于栈顶的时候自动取消广播接收器的注册
    @Override
    protected void onPause() {
        super.onPause();
        if(receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    class ForceOfflineReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //构建一个对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            //主题
            builder.setTitle("Warning");
            //内容
            builder.setMessage("You are forced to be offline. Please try to login again.");
            //false表示该对话框不可取消
            builder.setCancelable(false);

            builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //销毁所有活动
                    ActivityCollector.finishAll();
                    //跳转登录界面
                    Intent intent1 = new Intent(context, MainActivity.class);
                    context.startActivity(intent1);
                }
            });
            builder.show();
        }
    }

}
